package org.xiaov.framework.core;


import org.xiaov.framework.exception.BizException;
import org.xiaov.framework.util.IpUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * <p>
 * 描述：
 * </p>
 *
 * @author xiaovcloud
 * @since 2021/11/27 20:34
 */
public final class WebContext {
    /**
     * 设置 request
     *
     * @param request request
     */
    public static void setHttpRequest(HttpServletRequest request) {
        ThreadContext.setAttribute("HTTP_REQUEST", request);
    }

    /**
     * 设置 response
     *
     * @param response response
     */
    public static void setHttpRequest(HttpServletResponse response) {
        ThreadContext.setAttribute("HTTP_RESPONSE", response);
    }

    /**
     * 获取ip
     *
     * @return IP地址
     */
    public static String getIp() {
        HttpServletRequest request = getHttpServletRequest();
        return IpUtils.getIpAddress(request);
    }

    /**
     * 获取request
     *
     * @return request
     */
    public static HttpServletRequest getHttpServletRequest() {
        HttpServletRequest httpRequest = ThreadContext.getAttribute("HTTP_REQUEST", HttpServletRequest.class);
        if (httpRequest == null) {
            throw new BizException("请求非法！");
        }
        return httpRequest;
    }

    /**
     * 获取参数
     *
     * @param key key
     * @return value
     */
    public static String getParameter(String key) {
        return getHttpServletRequest().getParameter(key);
    }

    /**
     * 获取parameterMap
     *
     * @return Map<String, String [ ]>
     */
    public static Map<String, String[]> getParameterMap() {
        return getHttpServletRequest().getParameterMap();
    }

    /**
     * 根据key获取头部的值
     *
     * @param key key
     * @return value
     */
    public static String getHeader(String key) {
        return getHttpServletRequest().getHeader(key);
    }

    /**
     * 获取URI
     *
     * @return String
     */
    public static String getRequestURI() {
        return getHttpServletRequest().getRequestURI();
    }

    /**
     * 获取URI
     *
     * @return String
     */
    public static StringBuffer getRequestURL() {
        return getHttpServletRequest().getRequestURL();
    }
}
